package net.atomarrow.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author Boolone
 * @date 2020/1/15
 */
public class RequestUtil {

    /**
     * 获得请求体
     * @param request
     * @return
     */
    public static String getRequestBody(HttpServletRequest request) {
        StringBuilder content = new StringBuilder();
        String temp;
        try {
            BufferedReader reader = request.getReader();
            while ((temp = reader.readLine()) != null) {
                content.append(temp);
            }
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException("获取请求体内容发生异常", e);
        }
        return XssFilterUtil.stripXss(content.toString());
    }

    /**
     * 获取请求体内容，并转成JSONObject
     * @param request
     * @return
     */
    public static JSONObject getRequestBodyAsJSON(HttpServletRequest request) {
        return JSON.parseObject(getRequestBody(request));
    }


}
